package cn.com.checne.controller.superManager.synch;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.checne.constants.SynchConstants;
import cn.com.checne.util.HttpConnection;
import cn.com.checne.util.WebUtils;

@Controller
public class HeartBeatController {
	@RequestMapping( value=SynchConstants.HEARTBEATURL)
	public void heartBeat(HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();
			out.print("OK");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping( value="/synch/checkURL.do")
	public ModelAndView checkURL(HttpServletRequest request, ModelMap map) {
		ModelAndView mav = new ModelAndView("admin/websiteInfo/message");
		String message = "";
		String url = WebUtils.getRequestParameterAsString(request, "url");

		if ((StringUtils.isBlank(url)) || (url.endsWith("/"))) {
			message = "URL前缀不符合要求!";
			map.put("message", message);
			mav.addAllObjects(map);
			return mav;
		}

		StringBuilder checkURL = new StringBuilder(url);
		checkURL.append("/synch/heartbeat.do");
		String result = HttpConnection.sendPost(checkURL.toString(), "");
		if ((StringUtils.isNotBlank(result))
				&& (StringUtils.equalsIgnoreCase(result, "OK")))
			message = "验证有效!";
		else {
			message = "验证失败,请修改参数!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}
}